package com.sgb.kjwl.view.ui.activity.self.driver;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppProprietaryDriverDetailsActivityBinding;
import com.sgb.kjwl.model.entity.self.MotorcadeSimpleEntity;
import com.sgb.kjwl.model.entity.self.ProCarInfoEntity;
import com.sgb.kjwl.model.entity.self.ProDriverDetailsEntity;
import com.sgb.kjwl.model.entity.self.ProprietaryDriverEntity;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.transport.SelfCarDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.company.AddProprietaryFleetActivity;
import com.sgb.kjwl.view.ui.activity.transport.company.AffiliatedFleetDetailsActivity;
import com.sgb.kjwl.view.ui.adapter.self.ProCarListAdapter;
import com.sgb.kjwl.view.widget.transport.ChooseMotorcadeDialog;
import com.sgb.kjwl.viewmodel.self.driver.ProDriverDetailsModel;
import com.sgb.link.router.PathDriver;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.RoundDialog;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.sgb.link.router.PathDriver.ProprietaryDriverDetailsActivity;

/**
 * Describe:    自营司机详情（自营）
 * Author:  yangLei
 * Date:    2021/10/11
 */
@Route(path = ProprietaryDriverDetailsActivity)
public class ProprietaryDriverDetailsActivity extends BaseActivity<ProDriverDetailsModel, AppProprietaryDriverDetailsActivityBinding> {
    @Autowired(name = RouterKey.ID, desc = "司机No")
    public String no;
    private ProCarListAdapter carListAdapter;
    private List<ProCarInfoEntity> entities;

    private ProDriverDetailsEntity mDetails;
    private ChooseMotorcadeDialog editDialog;

    @Override
    protected int layoutId() {
        return R.layout.app_proprietary_driver_details_activity;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(ProDriverDetailsModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        initViews();
        initEvents();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(no)) {
            mViewModel.getDetails(this, no);
        } else {
            finish();
        }
    }

    private void initViews() {
        mBinding.includeTitle.titleView.setText("司机详情");

        if (UserOperating.getInstance().isTeam()) {//团队自营司机没有车队信息
            mBinding.motorcadeHint.setVisibility(View.GONE);
            mBinding.motorcadeName.setVisibility(View.GONE);
            mBinding.proprietaryMarker.setVisibility(View.GONE);
        } else if (UserOperating.getInstance().isCompany()) {
            mBinding.motorcadeHint.setVisibility(View.VISIBLE);
            mBinding.motorcadeName.setVisibility(View.VISIBLE);
            mBinding.proprietaryMarker.setVisibility(View.VISIBLE);
        }

        entities = new ArrayList<>();
        carListAdapter = new ProCarListAdapter(this, entities);
        mBinding.carList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        mBinding.carList.setAdapter(carListAdapter);
        carListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (entities != null && entities.size() > position)
                    SelfCarDetailActivity.start(ProprietaryDriverDetailsActivity.this, Long.parseLong(entities.get(position).getNo()));
            }
        });
        mBinding.carListLayout.setVisibility(View.VISIBLE);
    }

    private void initEvents() {
        mBinding.setOnClick(this);
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());

        mViewModel.detailsLD.observe(this, proDriverDetailsEntity -> {
            setDetails(proDriverDetailsEntity);
        });

        mViewModel.motorcadeListLD.observe(this, list -> {
            motorcadeListRequestResult(list);
        });

        mViewModel.unbindLD.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {//关系解绑成功
                mViewModel.getDetails(ProprietaryDriverDetailsActivity.this, no);
                EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
            }
        });

        mViewModel.deleteLD.observe(this, aBoolean -> {
            if (aBoolean != null && aBoolean) {//删除成功
                EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
                finish();
            }
        });
    }

    /**
     * 输入自营司机司机详情信息
     *
     * @param entity
     */
    @SuppressLint("ResourceAsColor")
    private void setDetails(ProDriverDetailsEntity entity) {
        if (entity != null) {
            mDetails = entity;
            if (!TextUtils.isEmpty(entity.getHeadImg())) {
                Glide.with(this).load(entity.getHeadImg())
                        .placeholder(R.drawable.icon_default_profile_photo_round)
                        .error(R.drawable.icon_default_profile_photo_round)
                        .into(mBinding.driverImg);
            }

            mBinding.driverName.setText(!TextUtils.isEmpty(entity.getName()) ? entity.getName() : "");
            if (!TextUtils.isEmpty(entity.getCarAge())) {
                mBinding.driverAge.setText(entity.getCarAge() + "岁");
                mBinding.driverAge.setVisibility(View.VISIBLE);
            } else {
                mBinding.driverAge.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(entity.getDriverAge())) {
                mBinding.driverYears.setText(entity.getDriverAge() + "年驾龄");
                mBinding.driverYears.setVisibility(View.VISIBLE);
            } else {
                mBinding.driverYears.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(entity.getIdCard())) {
                //只显示身份证前、后四位
                mBinding.idNum.setText(entity.getIdCard().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1****$2"));
            } else {
                mBinding.idNum.setText("/");
            }

            if (!TextUtils.isEmpty(entity.getMotorcadeName())) {
                mBinding.motorcadeName.setText(entity.getMotorcadeName() + " >");
                mBinding.motorcadeName.setTextColor(R.color.color_5792FD);
            } else {
                mBinding.motorcadeName.setText("/");
                mBinding.motorcadeName.setTextColor(R.color.color_ff666666);
            }

            //根据自营司机邀请状态，控制驾驶证、从业资格证的显示
            if (entity.getLinkState() != null) {
                if (entity.getLinkState() == 3) {
                    setCertificatesDisplayDefault(false);

                    if (!TextUtils.isEmpty(entity.getMainDriverLicense())) {
                        Glide.with(this)
                                .load(entity.getMainDriverLicense())
                                .placeholder(R.drawable.img_license_main_no_camera)
                                .into(mBinding.drivingLicenceMain);
                    }
                    if (!TextUtils.isEmpty(entity.getViceDriverLicense())) {
                        Glide.with(this)
                                .load(entity.getViceDriverLicense())
                                .placeholder(R.drawable.img_license_deputy_no_camera)
                                .into(mBinding.drivingLicenceDeputy);
                    }
                    //没有从业资格证显示，上传按钮
                    if (!TextUtils.isEmpty(entity.getMainCertificate()) && !TextUtils.isEmpty(entity.getViceCertificate())) {
                        Glide.with(this)
                                .load(entity.getMainCertificate())
                                .placeholder(R.drawable.img_cy_mian)
                                .into(mBinding.ivCertificatesMain);

                        Glide.with(this)
                                .load(entity.getViceCertificate())
                                .placeholder(R.drawable.img_cy_second_page)
                                .into(mBinding.ivCertificatesDeputy);

                        mBinding.qualificationCertificateInfoLayout.setVisibility(View.VISIBLE);
                        mBinding.uploadCertificate.setVisibility(View.GONE);
                    } else {
                        mBinding.qualificationCertificateInfoLayout.setVisibility(View.GONE);
                        mBinding.uploadCertificate.setVisibility(View.VISIBLE);
                    }
                } else {
                    setCertificatesDisplayDefault(true);
                }
            } else {
                setCertificatesDisplayDefault(true);
            }

            //驾驶证上的信息
            mBinding.licenceName.setText(!TextUtils.isEmpty(entity.getImageName()) ? entity.getImageName() : "/");
            mBinding.licenceNum.setText(!TextUtils.isEmpty(entity.getImageIdCard()) ? entity.getImageIdCard().replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1****$2") : "/");
            mBinding.fileNum.setText(!TextUtils.isEmpty(entity.getImageFileNumber()) ? entity.getImageFileNumber() : "/");
            mBinding.licenceCarType.setText(!TextUtils.isEmpty(entity.getImageQuasiDrivingModels()) ? entity.getImageQuasiDrivingModels() : "/");
            mBinding.validityDate.setText(entity.getImageValidityDate());

            if (entity.getCarInfo() != null && entity.getCarInfo().size() > 0) {
                entities.clear();
                entities.addAll(entity.getCarInfo());
                carListAdapter.notifyDataSetChanged();
                mBinding.carListLayout.setVisibility(View.VISIBLE);
            } else {
                mBinding.carListLayout.setVisibility(View.GONE);
            }

            if (UserOperating.getInstance().isTeam()) {
                mBinding.editTeamBtn.setVisibility(View.GONE);
            } else if (UserOperating.getInstance().isCompany()) {
                mBinding.editTeamBtn.setVisibility(View.VISIBLE);
            }

            mBinding.bottomBar.setVisibility(View.VISIBLE);
            //底部按钮根据司机的挂靠状态改变
            if (entity.getLinkState() != null) {
                //状态： 1 邀请中 2 已拒绝 3 已同意 4 已解除
                switch (entity.getLinkState()) {
                    case 1:
                        mBinding.unbindBtn.setVisibility(View.GONE);
                        mBinding.editTeamBtn.setBackgroundResource(R.drawable.bg_gradient_red_r0);
                        mBinding.editTeamBtn.setTextColor(Color.parseColor("#ffffff"));
                        if (UserOperating.getInstance().isTeam()) {
                            mBinding.bottomBar.setVisibility(View.GONE);
                        }

                        break;
                    case 3:
                        mBinding.unbindBtn.setText("解除关系");
                        mBinding.unbindBtn.setVisibility(View.VISIBLE);
                        mBinding.editTeamBtn.setBackgroundColor(getResources().getColor(R.color.transparent));
                        mBinding.editTeamBtn.setTextColor(Color.parseColor("#333333"));
                        break;
                    case 2:
                    case 4:
                        mBinding.unbindBtn.setText("删除");
                        mBinding.unbindBtn.setVisibility(View.VISIBLE);
                        mBinding.editTeamBtn.setBackgroundColor(getResources().getColor(R.color.transparent));
                        mBinding.editTeamBtn.setTextColor(Color.parseColor("#333333"));
                        break;

                    default:
                        mBinding.bottomBar.setVisibility(View.GONE);
                        break;

                }
            } else {
                mBinding.bottomBar.setVisibility(View.GONE);
            }
            mBinding.contentView.setVisibility(View.VISIBLE);

            //根据所属企业是否与车队，展示不同的车队编辑按钮
            if (entity.isHasMotorcade()){
                mBinding.editTeamBtn.setText("编辑所属车队");
            }else {
                mBinding.editTeamBtn.setText("添加车队");
            }

        } else {
            MToast.showToast(getApplicationContext(), "数据请求失败");
        }
    }

    /**
     * 设置运输证和驾驶证的显示状态
     *
     * @param show 是否显示占位图
     */
    private void setCertificatesDisplayDefault(boolean show) {
        if (!show) {
            //驾驶证
            mBinding.drivingLicenceMainTv.setText("主页");
            mBinding.drivingLicenceDeputyTv.setText("副页");
            //运输从业证
            mBinding.ivCertificatesMainTv.setText("主页");
            mBinding.ivCertificatesDeputyTv.setText("副页");
        } else {
            //驾驶证
            mBinding.drivingLicenceMainTv.setText("主页（司机同意后可见）");
            mBinding.drivingLicenceMain.setImageResource(R.drawable.img_license_main_no_camera);
            mBinding.drivingLicenceDeputyTv.setText("副页（司机同意后可见）");
            mBinding.drivingLicenceDeputy.setImageResource(R.drawable.img_license_deputy_no_camera);
            //运输从业证
            mBinding.ivCertificatesMainTv.setText("主页（司机同意后可见）");
            mBinding.ivCertificatesMain.setImageResource(R.drawable.img_cy_mian);
            mBinding.ivCertificatesDeputyTv.setText("副页（司机同意后可见）");
            mBinding.ivCertificatesDeputy.setImageResource(R.drawable.img_cy_second_page);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.motorcade_name://跳转所属车队详情
                if (!TextUtils.isEmpty(mDetails.getMotorcadeNo())) {
                    AffiliatedFleetDetailsActivity.start(this, true, mDetails.getMotorcadeNo());
                }
                break;

            case R.id.exchange_tab://与司机在线交流
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else if (mDetails != null && !TextUtils.isEmpty(mDetails.getImAccount())) {
//                    NimUIKit.startP2PSession(this, mDetails.getImAccount());
                    IMUtils.getInstance().buildSingleTalking(mDetails.getImAccount());
                }
                break;

            case R.id.call_phone_tab://联系司机
                if (!UserOperating.getInstance().isLogged()) {
                    VerificationCodeLoginActivity.start(this);
                } else if (mDetails != null && !TextUtils.isEmpty(mDetails.getTelphone())) {
                    new RoundDialog.Builder(this)
                            .title("确认呼叫")
                            .content(mDetails.getTelphone())
                            .confirm("确定")
                            .cancel("取消")
                            .cancelable(false)
                            .confirmCallback(on -> {
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + mDetails.getTelphone());
                                intent.setData(data);
                                startActivity(intent);
                            }).show();
                }

                break;

            case R.id.upload_certificate://上传道路运输从业资格证
                if (mDetails != null && !TextUtils.isEmpty(mDetails.getUserNo()))
                    ARouter.getInstance().build(PathDriver.UploadTransportQualificationCertificateActivity)
                            .withString(RouterKey.NO, mDetails.getUserNo())
                            .navigation(this, 200);
                break;

            case R.id.edit_team_btn://编辑车队
                if (mDetails.isHasMotorcade()){
                    mViewModel.requestMotorcadeList(this);
                }else {
                    //没有车队去添加
                    AddProprietaryFleetActivity.start(this, true);
                }
                break;

            case R.id.unbind_btn://解除绑定关系/删除
                clickUnbindBtn();
                break;

            case R.id.driving_licence_main:
                viewDriverLicense(0);
                break;
            case R.id.driving_licence_deputy:
                viewDriverLicense(1);
                break;

            case R.id.iv_certificates_main:
                viewDriverCertificates(0);
                break;
            case R.id.iv_certificates_deputy:
                viewDriverCertificates(1);
                break;
        }
    }

    private void viewDriverLicense(int position) {
        if (mDetails.getLinkState() != null && mDetails.getLinkState() == 3 && !TextUtils.isEmpty(mDetails.getMainDriverLicense()) && !TextUtils.isEmpty(mDetails.getViceDriverLicense())) {
            Intent intent = new Intent(this, PhotoViewActivity.class);
            List<String> url = new ArrayList<>();
            url.add(mDetails.getMainDriverLicense());
            url.add(mDetails.getViceDriverLicense());
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) url);
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
            startActivity(intent);
        }
    }

    private void viewDriverCertificates(int position) {
        if (mDetails.getLinkState() != null && mDetails.getLinkState() == 3 && !TextUtils.isEmpty(mDetails.getMainCertificate()) && !TextUtils.isEmpty(mDetails.getViceCertificate())) {
            Intent intent = new Intent(this, PhotoViewActivity.class);
            List<String> url = new ArrayList<>();
            url.add(mDetails.getMainCertificate());
            url.add(mDetails.getViceCertificate());
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) url);
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
            startActivity(intent);
        }
    }

    /**
     * 根据自营司机邀请状态处理关系
     */
    private void clickUnbindBtn() {
        if (mDetails == null || mDetails.getLinkState() == null)
            return;
        switch (mDetails.getLinkState()) {
            case 3://已同意，需要解除关系
                if (mDetails != null && !TextUtils.isEmpty(no)) {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content("解除关系后，绑定该司机的车辆将被解绑。您确定要解除关系吗？")
                            .confirm("确定")
                            .cancel("取消")
                            .singleBtn(false)
                            .cancelable(false)
                            .confirmCallback(v -> mViewModel.unbindDriver(no))
                            .show();
                }
                break;

            case 2:
            case 4:
                //已拒绝和已解除直接进行删除
                if (mDetails != null && !TextUtils.isEmpty(mDetails.getName()) && !TextUtils.isEmpty(no)) {
                    new RoundDialog.Builder(this)
                            .title("提示")
                            .content("您确定要删除司机" + mDetails.getName() + "吗？")
                            .confirm("确定")
                            .cancel("取消")
                            .singleBtn(false)
                            .cancelable(false)
                            .confirmCallback(v -> mViewModel.deleteDriver(no))
                            .show();
                }
                break;
        }
    }

    @SuppressLint("ResourceAsColor")
    private void motorcadeListRequestResult(List<MotorcadeSimpleEntity> list) {
        if (list == null || list.size() < 1) {
            //没有车队时弹窗提示
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("当前无可用车队，请先至“车队管理”添加自营车队")
                    .confirm("确定")
                    .singleBtn(true)
                    .cancelable(false)
                    .show();
        } else {
            //有车队可选
            ChooseMotorcadeDialog.setDefaultItem(list, mDetails.getMotorcadeNo());
            if (editDialog == null) {
                editDialog = ChooseMotorcadeDialog.newInstance(this, 0, list);
                editDialog.setResultListener(entity -> {
                    if (entity != null && !TextUtils.isEmpty(entity.getMotorcadeNo()) && !TextUtils.isEmpty(entity.getMotorcadeName())) {
                        mDetails.setMotorcadeNo(entity.getMotorcadeNo());
                        mDetails.setMotorcadeName(entity.getMotorcadeName());
                        mBinding.motorcadeName.setText(entity.getMotorcadeName() + " >");
                        mBinding.motorcadeName.setTextColor(R.color.color_5792FD);
                    } else {
                        mBinding.motorcadeName.setText("/");
                        mBinding.motorcadeName.setTextColor(R.color.color_ff666666);
                        mDetails.setMotorcadeName("");
                        mDetails.setMotorcadeNo("");
                    }
                });
            } else {
                editDialog.setMotorcades(list);
            }
            editDialog.show();
            editDialog.setTitle("编辑所属车队");
            ProprietaryDriverEntity driverEntity = new ProprietaryDriverEntity();
            driverEntity.setMotorcadeName(mDetails.getMotorcadeName());
            driverEntity.setMotorcadeNo(mDetails.getMotorcadeNo());
            driverEntity.setDriverNo(mDetails.getUserNo());
            editDialog.setDriverInfo(driverEntity);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 200) {
            //上传运输资格证成功，回调刷新页面
            mViewModel.getDetails(this, no);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (editDialog != null && editDialog.isShowing()) {
            editDialog.dismiss();
            editDialog = null;
        }
    }
}
